import {
  Block,
  View,
  Image,
  ScrollView,
  Text,
  Button,
  Textarea
} from "@tarojs/components";
import Taro from "@tarojs/taro";
import withWeapp from "@tarojs/with-weapp";
import Page from "../../component/page";
import "./index.scss";
import ParseComponent from "../../component/WxParseComponent.js";
import { AtTag, AtTextarea, AtButton, AtIcon } from "taro-ui";

import { host as BASE_API } from '../../utils/config'

const modules = require("./module.js");
const flow = require("../../utils/flow.js");
const { rpc, app, format, fromNowOn } = require("../../utils/util.js");
const service = require("./service.js");
const regeneratorRuntime = require("../../utils/async.js");

const DEFALUT_AVATAR = require("../../icons/avatar.png")

@withWeapp("Page")
class _C extends Taro.Component {
  state = {
    logs: [],
    replayValue: "",
    comments: [],
    userInfo: {},
    commentVisible: false,
    statusBarHeight: app.globalData.statusBarHeight,
    contentHeight: app.globalData.contentHeight,
    showLoading: true,
    headerHeight: app.globalData.headerHeight,
    scrollToComment: 0
  };
  onReplayInput = event => {
    // this.setState({ replayValue: event.detail.value });
    this.setState({ replayValue: event.target.value });
  };

  onGotUserInfo = e => {
    // console.log("1111111111111111", e.detail.userInfo)
    if (e.detail.userInfo) {
      this.setState({
        commentVisible: true,
        userInfo: e.detail.userInfo
      });
      Taro.request({
        url: `${BASE_API}/me`,
        header: {
          Authorization: "token " + Taro.getApp().globalData.token,
          "content-type": "application/x-www-form-urlencoded"
        },
        method: "post",
        data: e.detail.userInfo
      });
    }
  };
  onReplayConfirm = () => {
    const { replayValue, id } = this.data;
    // console.log("this.data:", replayValue);
    if (!replayValue) {
      return;
    }
    Taro.request({
      url: `${BASE_API}/comment`,
      method: "post",
      data: {
        share_id: id,
        commentbody: replayValue
      },
      header: {
        Authorization: "token " + app.globalData.token,
        "content-type": "application/x-www-form-urlencoded"
      },
      success: result => {
        const { id, commentnum } = this.data;
        Taro.showToast("评论发布成功^_^");
        this.refreshComment(id).then(() => {
          this.setState({
            commentnum: commentnum+1
          })
        })
        this.clickMask()
      }
    });
  };
  
  tapThumb = (id, type) => {
    let { comments = [] } = this.data;
    const index = comments.findIndex(com => com.id === id);
    const comment = comments.find(com => com.id === id);
    const { isLiking, isDisliking } = comment

    let api = 'addlike'
    if (type === 'like') {
      api = isLiking ? 'dellike' : 'addlike'
    } else if (type === 'dislike') {
      api = isDisliking ? 'deldislike' : 'adddislike'
    }

    Taro.request({
      url: `${BASE_API}/like/${api}`,
      header: {
        Authorization: "token " + Taro.getApp().globalData.token,
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "post",
      data: {
        entity_id: id,
        entity_type: "comment"
      },
      success: (res) => {
        if (index !== -1) {
          const {likenum, dislikenum } = res.data.data
          comment.likeNum = likenum;
          comment.dislikeNum = dislikenum

          comment.isLiking = type === 'like' ? !isLiking : isLiking,
          comment.isDisliking = type === 'dislike' ? !isDisliking : isDisliking

          comments.splice(index, 1, comment);
          this.setState({ comments });
        }
      },
      fail: function () {
        Taro.showToast({
          icon: "none",
          title: "系统开始了小差..请重试"
        });
      }
    });
  };

  addLikeToAriticle = (type) => {
    console.log("this.state", this.state)
    const { id, is_liking, is_disliking } = this.state

    let api = 'addlike'
    if (type === 'like') {
      api = is_liking ? 'dellike' : 'addlike'
    } else if (type === 'dislike') {
      api = is_disliking ? 'deldislike' : 'adddislike'
    }

    Taro.request({
      url: `${BASE_API}/like/${api}`,
      header: {
        Authorization: "token " + Taro.getApp().globalData.token,
        "content-type": "application/x-www-form-urlencoded"
      },
      method: "post",
      data: {
        entity_id: id,
        entity_type: "share"
      },
      success: (res) => {
        const {likenum, dislikenum } = res.data.data
        this.setState({
          likenum: likenum,
          dislikenum: dislikenum,
          is_liking: type === 'like' ? !is_liking : is_liking,
          is_disliking: type === 'dislike' ? !is_disliking : is_disliking
        })
      },
      fail: function () {
        Taro.showToast({
          icon: "none",
          title: "系统开始了小差..请重试"
        });
      }
    });
  };

  back = () => {
    Taro.navigateBack({ url: "../index/index" });
  };

  componentWillMount = async page => {
    this.flow = new flow(
      this,
      modules
    );
    this.init(this.$router.params);
    wx.showShareMenu({
      withShareTicket: true
    });
  };
  init = async page => {
    const that = this;
    if (!page.id) return;

    console.log("当前文章id:", page.id);

    this.flow && (await this.flow.dispatch("getContent", { that, id: page.id }));

    this.refreshComment(page.id)
  };

  // 刷新评论列表区域
  refreshComment = (id) => {
    return rpc(service.getComments, {
      share_id: id,
      entity_type: "share"
    }).then(data => {
      const { comments = [] } = data;
      this.setState({
        comments: comments.map(comment => ({
          ...comment,
          commenttime: fromNowOn(new Date(comment.pushlished))
        }))
      });
    });
  }

  config = {
    navigationBarTitleText: ""
  };

  scrollToCommentArea = () => {
    Taro.createSelectorQuery()
      .select('#content-wrap')
      .boundingClientRect(rect => {
        Taro.pageScrollTo({
          scrollTop: rect.height
        })
      })
      .exec()
  }

  // 点击弹窗，失去焦点
  clickMask = () => {
    this.setState({
      commentVisible: false
    })
  }

  render() {
    const {
      showLoading,
      headerHeight,
      contentHeight,
      title,
      author,
      tags = [],
      published,
      markdown,
      comments,
      replayValue,
      commentVisible,
      commentnum,
      is_liking,
      is_disliking,
      likenum,
      dislikenum,
      scrollToComment = 0
    } = this.state

    return (
      <View>
        <Page
          onClickLeftIcon={this.back}
          leftIconType="chevron-left"
          leftText="返回"
          title="文章详情"
        />

        <ScrollView className="container log-list" style={`padding: ${headerHeight || 0}px 0 60px 0`}>
          <View className="content-shadow1" />
          <View className={"content content-loading " + (showLoading ? "show" : "hide")} style={"height: " + contentHeight + "px"}>
            <Image src={require("../../icons/loading.gif")} style="width: 40px; height:40px" />
          </View>
          <View id="content-wrap" className={"content " + (showLoading ? "hide" : "show")}>
            <View className="at-article">
              <View className="at-article__h1 art-title">{title}</View>
              <View className="art-tags">
                {
                  tags.length && tags.map(t => (
                    <AtTag className="art-tag" size="small" active={true}>{t}</AtTag>
                  ))
                }
              </View>
              <View className="at-article__info art-info">{author || '匿名'} 发布于 {published}</View>
            </View>

            <View className="content-ctx">
              <ParseComponent mark={markdown} />
            </View>
          </View>

          <View id="comment-wrap" className={"replay-container " + (showLoading ? "hide" : "show")}>
            <Text className="replay-label">评论</Text>
            {comments.length === 0 && (
              <View className="no-comment">暂无评论，有空沙发！</View>
            )}
            {comments.map((item, index) => {
              return (
                <View>
                  <View className='at-article replay-box'>
                    <View className="detail-header">
                      <View className="left">
                        <Image className="avatar" src={item.avatar || DEFALUT_AVATAR} />
                      </View>
                      <View className="middle">
                        <View className='at-article__h3'>{item.user_name || '匿名'}</View>
                        <View className='at-article__info'>{index + 1 + "楼"} {item.commenttime}</View>
                      </View>
                      <View className="right">
                        <View className="toucher" data-sid={item.id} onClick={this.tapThumb.bind(this, item.id, 'like')}>
                          <AtIcon prefixClass='icon' value='dianzanqian' size={17} color={item.isLiking ? '#ea9518' : '#bbb'}></AtIcon>
                          <Text className={`num ${item.isLiking ? 'orange' : ''}`}>{item.likeNum || ''}</Text>
                        </View>
                        <View className="toucher" onClick={this.tapThumb.bind(this, item.id, 'dislike')}>
                          <AtIcon prefixClass='icon' value='dislike' size={17} color={item.isDisliking ? '#ea9518' : '#bbb'}></AtIcon>
                          <Text className={`num ${item.isDisliking ? 'orange' : ''}`}>{item.dislikeNum || ''}</Text>
                        </View>
                      </View>
                    </View>
                    <View className='at-article__p'>{item.content}</View>
                  </View>
                  
                </View>
              );
            })}
          </View>
          
        </ScrollView>

        {/* 评论 */}
        <View className="comment-footer">
          {commentVisible ? (
            <View className="replay-area">
              <AtTextarea
                placeholder='来说两句吧...'
                value={replayValue}
                autoFocus={true}
                maxLength={500}
                height={100}
                fixed={true}
                onChange={this.onReplayInput.bind(this)} />
              <AtButton className="send" type='primary' size='small' onClick={this.onReplayConfirm}>发送</AtButton>
            </View>
          ) : (
              <View className='at-row fixed-footer'>
                <View className='at-col at-col-6 r-wrap'>
                  <Button className="replay-btn" open-type="getUserInfo" onGetUserInfo={this.onGotUserInfo}>来说两句吧...</Button>
                </View>
                <View className='at-col at-col-2 r-wrap'>
                  <Button className="r-btn-wrap" onClick={this.scrollToCommentArea}>
                    <AtIcon prefixClass='icon' value='pinglun' size={21} color='#bbb'></AtIcon>
                    <Text className="num">{commentnum || ''}</Text>
                  </Button>
                </View>
                <View className='at-col at-col-2 r-wrap'>
                  <Button className="r-btn-wrap" onGetUserInfo={this.onGotUserInfo} onClick={this.addLikeToAriticle.bind(this, 'like')}>
                    <AtIcon prefixClass='icon' value='dianzanhou' size={21} color={is_liking ? '#ea9518' : '#bbb'}></AtIcon>
                    <Text className={`num ${is_liking ? 'orange' : ''}`}>{likenum || ''}</Text>
                  </Button>
                </View>
                <View className='at-col at-col-2 r-wrap'>
                  <Button className="r-btn-wrap" onGetUserInfo={this.onGotUserInfo} onClick={this.addLikeToAriticle.bind(this, 'dislike')}>
                    <AtIcon prefixClass='icon' value='buxihuan' size={21} color={is_disliking ? '#ea9518' : '#bbb'}></AtIcon>
                    <Text className={`num ${is_disliking ? 'orange' : ''}`}>{dislikenum || ''}</Text>
                  </Button>
                </View>
              </View>
            )}
        </View>
        <View className={`mask ${commentVisible ? "show" : ""}`} onClick={this.clickMask}></View>
      </View>
    );
  }
}

export default _C;
